/**
 * WebSocket数据管理模块
 */
import deviceWebSocketService from '@/utils/websocket'
import { getWebSocketStatus } from '@/api/real/detect'

const state = {
  // 连接状态
  isConnected: false,
  isConnecting: false,
  reconnectAttempts: 0,
  connectionError: null,

  // 服务器WebSocket状态
  serverStatus: {
    onlineCount: 0,
    isEnabled: false
  },

  // 设备状态数据
  deviceStatus: [],

  // 设备信息数据
  deviceInfo: [],

  // 最后更新时间
  lastUpdateTime: null,

  // 消息历史
  messageHistory: []
}

const mutations = {
  // 设置连接状态
  SET_CONNECTION_STATE(state, { isConnected, isConnecting, reconnectAttempts }) {
    state.isConnected = isConnected
    state.isConnecting = isConnecting
    state.reconnectAttempts = reconnectAttempts
  },

  // 设置连接错误
  SET_CONNECTION_ERROR(state, error) {
    state.connectionError = error
  },

  // 设置服务器状态
  SET_SERVER_STATUS(state, status) {
    state.serverStatus = status
  },

  // 更新设备状态
  UPDATE_DEVICE_STATUS(state, statusData) {
    if (Array.isArray(statusData)) {
      state.deviceStatus = statusData
    } else {
      // 单个设备状态更新
      const index = state.deviceStatus.findIndex(item => item.deviceId === statusData.deviceId)
      if (index !== -1) {
        state.deviceStatus.splice(index, 1, statusData)
      } else {
        state.deviceStatus.push(statusData)
      }
    }
    state.lastUpdateTime = new Date()
  },

  // 更新设备信息
  UPDATE_DEVICE_INFO(state, infoData) {
    if (Array.isArray(infoData)) {
      state.deviceInfo = infoData
    } else {
      // 单个设备信息更新
      const index = state.deviceInfo.findIndex(item => item.deviceId === infoData.deviceId)
      if (index !== -1) {
        state.deviceInfo.splice(index, 1, infoData)
      } else {
        state.deviceInfo.push(infoData)
      }
    }
    state.lastUpdateTime = new Date()
  },

  // 添加消息历史
  ADD_MESSAGE_HISTORY(state, message) {
    state.messageHistory.unshift({
      ...message,
      timestamp: new Date()
    })

    // 保持历史记录在合理范围内
    if (state.messageHistory.length > 100) {
      state.messageHistory = state.messageHistory.slice(0, 100)
    }
  },

  // 清空数据
  CLEAR_DATA(state) {
    state.deviceStatus = []
    state.deviceInfo = []
    state.messageHistory = []
    state.lastUpdateTime = null
  }
}

const actions = {
  // 初始化WebSocket连接
  async initWebSocket({ commit, dispatch }) {
    try {
      // 先查询服务器WebSocket状态
      await dispatch('fetchServerStatus')

      // 设置事件监听器
      deviceWebSocketService.on('connected', () => {
        commit('SET_CONNECTION_STATE', {
          isConnected: true,
          isConnecting: false,
          reconnectAttempts: 0
        })
        commit('SET_CONNECTION_ERROR', null)
      })

      deviceWebSocketService.on('disconnected', () => {
        commit('SET_CONNECTION_STATE', {
          isConnected: false,
          isConnecting: false,
          reconnectAttempts: deviceWebSocketService.reconnectAttempts
        })
      })

      deviceWebSocketService.on('error', (error) => {
        commit('SET_CONNECTION_ERROR', error)
        commit('SET_CONNECTION_STATE', {
          isConnected: false,
          isConnecting: false,
          reconnectAttempts: deviceWebSocketService.reconnectAttempts
        })
      })

      deviceWebSocketService.on('deviceStatusUpdate', (data) => {
        commit('UPDATE_DEVICE_STATUS', data)
        commit('ADD_MESSAGE_HISTORY', {
          type: 'DEVICE_STATUS_UPDATE',
          data
        })
      })

      deviceWebSocketService.on('deviceInfoUpdate', (data) => {
        commit('UPDATE_DEVICE_INFO', data)
        commit('ADD_MESSAGE_HISTORY', {
          type: 'DEVICE_INFO_UPDATE',
          data
        })
      })

      deviceWebSocketService.on('reconnectFailed', () => {
        commit('SET_CONNECTION_ERROR', '重连失败，请检查网络连接')
      })

      // 开始连接
      commit('SET_CONNECTION_STATE', {
        isConnected: false,
        isConnecting: true,
        reconnectAttempts: 0
      })

      const wsUrl = process.env.VUE_APP_WS_URL || 'ws://localhost:8081/ws/device-monitor'
      deviceWebSocketService.connect(wsUrl)

    } catch (error) {
      console.error('初始化WebSocket失败:', error)
      commit('SET_CONNECTION_ERROR', error.message)
    }
  },

  // 断开WebSocket连接
  disconnectWebSocket({ commit }) {
    deviceWebSocketService.disconnect()
    commit('SET_CONNECTION_STATE', {
      isConnected: false,
      isConnecting: false,
      reconnectAttempts: 0
    })
    commit('CLEAR_DATA')
  },

  // 重新连接
  reconnectWebSocket({ dispatch }) {
    deviceWebSocketService.reconnect()
  },

  // 获取服务器WebSocket状态
  async fetchServerStatus({ commit }) {
    try {
      const response = await getWebSocketStatus()
      commit('SET_SERVER_STATUS', response.data)
      return response.data
    } catch (error) {
      console.error('获取WebSocket服务器状态失败:', error)
      throw error
    }
  },

  // 发送消息
  sendMessage({ state }, message) {
    if (state.isConnected) {
      deviceWebSocketService.send(message)
    } else {
      throw new Error('WebSocket未连接')
    }
  }
}

const getters = {
  // 连接状态信息
  connectionInfo: (state) => ({
    isConnected: state.isConnected,
    isConnecting: state.isConnecting,
    reconnectAttempts: state.reconnectAttempts,
    error: state.connectionError
  }),

  // 获取指定设备的状态
  getDeviceStatus: (state) => (deviceId) => {
    return state.deviceStatus.find(item => item.deviceId === deviceId)
  },

  // 获取指定设备的信息
  getDeviceInfo: (state) => (deviceId) => {
    return state.deviceInfo.find(item => item.deviceId === deviceId)
  },

  // 获取所有在线设备
  onlineDevices: (state) => {
    return state.deviceStatus.filter(item => item.status === '正常' || item.status === 'online')
  },

  // 获取异常设备
  abnormalDevices: (state) => {
    return state.deviceStatus.filter(item => item.status !== '正常' && item.status !== 'online')
  },

  // 是否有实时数据
  hasRealtimeData: (state) => {
    return state.deviceStatus.length > 0 || state.deviceInfo.length > 0
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
